/**
 * 
 */
package org.istt.dao.hibernate;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;
import org.istt.dao.FieldDao;
import org.istt.domain.Field;
import org.istt.domain.File;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

/**
 * This class interacts with Spring and Hibernate to save and
 * retrieve Field objects.
 *
 * @author NDTHO
 */
@Repository(value = "fieldDao")
public class FieldDaoHibernate extends BaseDaoHibernate<Field, Long> implements FieldDao {
    Log logger = LogFactory.getLog(FieldDaoHibernate.class);
    
    @Autowired
    public FieldDaoHibernate(SessionFactory sessionFactory) {
		super(sessionFactory);
	}
    
	public List<Field> getFields() {
        return findAll();
    }

    public Field getField(Long id) {
    	Field field = findById(id, false);
        if (field == null) {
            throw new ObjectRetrievalFailureException(Field.class, id);
        }
        return field;
    }

    public void saveField(Field field) {
        makePersistent(field);

        if (logger.isDebugEnabled()) {
            logger.debug("fieldId set to: " + field.getId());
        }
    }

    public void removeField(Long id) {
    	makeTransient(getField(id));
    }

	@SuppressWarnings("unchecked")
	@Override
	public List<Field> searchField(final String name) {
		
		return (List<Field>) hibernateTemplate.execute(new HibernateCallback<Object>() {
			@Override
			public Object doInHibernate(Session session) throws HibernateException,	SQLException {
						Criteria criteria = session.createCriteria(Field.class);
						if(name!=null && !"".equals(name)) criteria.add(Restrictions.ilike("name", "%"+name+"%"));
						return criteria.list();
			}
		});
	}

	@Override
	public Field getFieldByDepartment(final Long depID) {
		// TODO Auto-generated method stub
		return (Field) hibernateTemplate.execute(new HibernateCallback<Object>() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				@SuppressWarnings("unchecked")
				List<Field> result = session.createCriteria(Field.class)
						.add(Example.create(new Field()))
						.createCriteria("department")
						.add(Restrictions.idEq(depID)).list();
				if(result.size()!=0)
					return result.get(0);
				else return null;
			}
		});
	}
}
